#/bin/sh

FILE=$1 #this file hold a list of files to be sync
SourceFolder=$2 #source folder
DestiFolder=$3  #destifolder

#------------------parameter check
bValidParam=1
if [ -z $FILE ] || [ -z $SourceFolder ] || [ -z $DestiFolder ];
then
	bValidParam=0
fi


if [ ! -f $FILE ] || [ ! -d $SourceFolder ] || [ ! -d $DestiFolder ];
then
	bValidParam=0
fi

if [ $bValidParam == 0 ];
then
	echo "How to use:"
	echo "	$(basename $0) 'file' 'SourceFolder' 'DestinationFolder'"
	exit 0
fi

#-----------------create a log file
LogFile=./SyncLog
Num=1
while [ -f $LogFile$Num ]
do
	Num=$[ $Num +1]
done
LogFile=$LogFile$Num
echo "create log file $LogFile"
touch $LogFile #create the log file 
echo "------------------$(date) $(basename $0) $FILE $SourceFolder $DestinationFolder" >> $LogFile

#-----------------Show info
echo "The App will copy files listed in $FILE "
echo "		from  source    folder $SourceFolder"
echo " 		to destination  folder $DestiFolder"
read -p "do you want to continue> y/n:" answer
case $answer in
	y)
		;;
	n)
		echo "exit for choosing no continue"
		exit 0
		;;
	*)
		echo "exit for invalid choice"
		exit 0
		;;
esac

#-----------------Sync files
bFailed=0
TMPFILE=./syncFileTmpFile12345
touch $TMPFILE
for strFile in $(cat $FILE)
do 
	bSource=0 # if the source file exist
	bDesti=0 #if the destination file exist
	bFile=0  #if the file with relative path exist
	if [  -f $strFile ];
	then
		bFile=1
	fi

	if [ -f $SourceFolder/$strFile ];
	then
		bSource=1
	fi

	if [ -f $DestiFolder/$strFile ];
	then
		bDesti=1
	fi

	if [ $bSource -eq 1 -a $bDesti -eq 1 -a $bFile -eq 1 ];
	then
		echo $strFile >> $LogFile

		cp $SourceFolder/$strFile $DestiFolder/$strFile 
	else
		bFailed=1
		echo $strFile >> $TMPFILE
	fi
done

if [ $bFailed == 1 ]; #some files failed to be synced
then
	echo "*************Failed List" >> $LogFile
	cat $TMPFILE>>$LogFile
	rm $TMPFILE
fi

exit 0
